<template>
  <div>
    <h2>预约管理</h2>
    <div class="search-bar">
      <input
          type="text"
          v-model="searchPhone"
          placeholder="输入电话号码"
      />
      <button @click="searchAppointments">Search</button>
    </div>
    <!-- 预约表格 -->
    <table>
      <thead>
      <tr>

        <th>用户ID</th>
        <th>车辆ID</th>
        <th>电话号码</th>
        <th>预约日期</th>
        <th>状态</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="appointment in appointments" :key="appointment.appointmentId">

        <td>{{ appointment.userId }}</td>
        <td>{{ appointment.productId }}</td>
        <td>{{ appointment.telephone }}</td>
        <td>{{ formatDate(appointment.appointmentDate) }}</td>
        <td @click.stop="editStatus(appointment)" ref="statusCell">
            <span v-if="editingAppointmentId !== appointment.appointmentId">
              {{ formatStatus(appointment.status) }}
            </span>
          <select
              v-else
              v-model="appointment.status"
              @change="saveStatus(appointment)"
              ref="statusSelect"
          >
            <option value="1">已预约</option>
            <option value="2">已试驾</option>
            <option value="3">已过期</option>
          </select>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <Pagination
        :current-page="currentPageNumber"
        :total="totalAppointments"
        :page-size="pageSize"
        @update:currentPage="handlePageChange"
    />
  </div>
</template>

<script>
import {onBeforeUnmount, onMounted, ref} from 'vue';
import axios from 'axios';
import Pagination from '@/components/Pagination.vue';

export default {
  components: {
    Pagination,
  },
  props: {
    currentPageNumber: {
      type: Number,
      required: true,
    },
    pageSize: {
      type: Number,
      required: true,
    },
  },
  setup(props, { emit }) {
    const appointments = ref([]);
    const totalAppointments = ref(0);
    const searchUserId = ref('');
    const searchPhone = ref('');
    const searchProductId = ref('');
    const editingAppointmentId = ref(null);
    const statusCellRef = ref(null);// 跟踪正在编辑状态的预约ID

    // 请求预约数据
    const fetchAppointments = async (pageNum, pageSize, userId = '', productId = '',telephone='') => {
      try {
        const response = await axios.post('/admins/selectAllAppointments', {
          pageNum,
          pageSize,
          userId,
          productId,
          telephone
        });
        appointments.value = response.data.records;
        totalAppointments.value = response.data.total;
      } catch (error) {
        console.error('Failed to fetch appointments:', error);
      }
    };
    // 进入编辑状态
    const editStatus = (appointment) => {
      editingAppointmentId.value = appointment.appointmentId;
    };

    // 保存状态
    const saveStatus = async (appointment) => {
      try {
        await axios.post('/admins/updateAppointmentStatus', {
          appointmentId: appointment.appointmentId,
          status: appointment.status,
        });
        console.log('Status updated successfully');
        editingAppointmentId.value = null; // 退出编辑模式
      } catch (error) {
        console.error('Failed to update status:', error);
      }
    };

    // 检测点击是否发生在选择框外
    const handleClickOutside = (event) => {
      const statusSelect = statusCellRef.value?.querySelector('select');
      if (statusSelect && !statusSelect.contains(event.target)) {
        editingAppointmentId.value = null;
      }
    };

    // 监听全局点击事件
    onMounted(() => {
      document.addEventListener('click', handleClickOutside);
    });

    onBeforeUnmount(() => {
      document.removeEventListener('click', handleClickOutside);
    });


    // 搜索预约
    const searchAppointments = () => {
      fetchAppointments(props.currentPageNumber, props.pageSize, searchUserId.value, searchProductId.value,searchPhone.value);
    };

    // 处理分页更改
    const handlePageChange = (newPage) => {
      emit('update:currentPageNumber', newPage);
      fetchAppointments(newPage, props.pageSize, searchUserId.value, searchProductId.value);
    };

    // 初始化时加载预约数据
    fetchAppointments(props.currentPageNumber, props.pageSize);

    const formatStatus = (status) => {
      return ['0', '已预约', '已试驾','已过期',][status] || '未知状态';
    };

    const formatDate = (date) => {
      const d = new Date(date);
      return d.toLocaleDateString();
    };

    return {
      appointments,
      totalAppointments,
      searchUserId,
      searchProductId,
      searchAppointments,
      handlePageChange,
      formatStatus,
      formatDate,
      searchPhone,
      editStatus,
      saveStatus,
      editingAppointmentId

    };
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

table th,
table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
</style>
